package com.echo.im.infrastructure.mq.event.producer;

import com.alibaba.fastjson2.JSON;
import com.echo.im.infrastructure.mq.event.BaseEvent;
import com.echo.im.common.enums.TaskStateEnum;

import com.echo.im.repository.dao.entity.Task;
import com.echo.im.repository.dao.mapper.TaskMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description 消息发送
 * @create 2024-03-30 12:40
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EventPublisher {

    private final RabbitTemplate rabbitTemplate;
    private final TaskMapper taskDao;

    public <T extends BaseEvent<K>, K> void publishWithServerId(T baseEvent, K data, String serverId) {
        publish(baseEvent.exchange(),baseEvent.topic()+"."+serverId,baseEvent.buildEventMessage(data));
    }

    public <T extends BaseEvent<K>, K> void publish(T baseEvent,K data) {
        publish(baseEvent.exchange(),baseEvent.topic(),baseEvent.buildEventMessage(data));
    }

    public void publish(String exchange,String topic, BaseEvent.EventMessage<?> eventMessage) {
        try {
            String messageJson = JSON.toJSONString(eventMessage);
            rabbitTemplate.convertAndSend(exchange,topic, messageJson);
            log.info("发送MQ消息 topic:{} model:{}", topic, messageJson);
        } catch (Exception e) {
            Task task = new Task();
            task.setExchange(exchange);
            task.setTopic(topic);
            task.setMessageId(null);
            task.setMessage(JSON.toJSONString(eventMessage));
            task.setState(TaskStateEnum.fail.getCode());
            taskDao.insert(task);
            log.error("发送MQ消息失败 topic:{} model:{}", topic, JSON.toJSONString(eventMessage), e);
            throw e;
        }
    }

    public void publish(String exchange,String topic, String eventMessage) {
        try {
            String messageJson = eventMessage;
            rabbitTemplate.convertAndSend(exchange,topic, messageJson);
            log.info("发送MQ消息 topic:{} model:{}", topic, messageJson);
        } catch (Exception e) {
            Task task = new Task();
            task.setExchange(exchange);
            task.setTopic(topic);
            task.setMessageId(null);
            task.setMessage(JSON.toJSONString(eventMessage));
            task.setState(TaskStateEnum.fail.getCode());
            taskDao.insert(task);
            log.error("发送MQ消息失败 topic:{} model:{}", topic, JSON.toJSONString(eventMessage), e);
            throw e;
        }
    }

}
